import React, { useState,useRef,useEffect} from 'react';
import { useNavigate } from 'react-router-dom'
import axios from 'axios';
import Navbar from './components/Navbar';
import './User.css';


function User() {
  const [activeTab, setActiveTab] = useState('query');
  const [queryHistory, setQueryHistory] = useState([]);
  const [generateHistory, setGenerateHistory] = useState([]);
  const [loading, setLoading] = useState(true);
  const userId = localStorage.getItem('userId');

  const fetchData = async () => {
    setLoading(true);
    try {
      if (activeTab === 'query') {
        const res = await axios.get('http://localhost:8080/history/query', {
          params: { userId },
          headers: { Authorization: localStorage.getItem('token') }
        });
        setQueryHistory(res.data.data || []);//null就用空数组代替
      } else {
        const res = await axios.get('http://localhost:8080/history/generate', {
          params: { userId },
          headers: { Authorization: localStorage.getItem('token') }
        });
        setGenerateHistory(res.data.data || []);
      }
    } catch (error) {
      console.error('加载历史失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [activeTab]);

  return (
    <div>
      <Navbar />
    <div className="dashboard-container">
      <h2>用户后台</h2>
      <div className="tab-bar">
        <button className={activeTab === 'query' ? 'active' : ''} onClick={() => setActiveTab('query')}>查询历史</button>
        <button className={activeTab === 'generate' ? 'active' : ''} onClick={() => setActiveTab('generate')}>生成历史</button>
      </div>

      {loading ? (
        <p>加载中...</p>
      ) : (
        <table className="history-table">
          <thead>
            <tr>
              <th>内容</th>
              <th>时间</th>
              {activeTab === 'query' && <th>搜索类型</th>}
            </tr>
          </thead>
          <tbody>
            {(activeTab === 'query' ? queryHistory : generateHistory).map((item, index) => (
              <tr key={index}>
                <td>{item.query || item.input || '—'}</td>
                <td>{new Date(item.date).toLocaleString()}</td>
                {activeTab === 'query' && <td>{item.type}</td>}
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
    </div>
  );
}
 export default User;